//
//  AQUpgradeView.m
//  AiQiu
//
//  Created by ChenYuan on 2020/6/13.
//  Copyright © 2020 lesports. All rights reserved.
//

#import "AQUpgradeView.h"
#import "Masonry.h"

/*******颜色规范*******/
#define RGBA_COLOR(R, G, B, A) [UIColor colorWithRed:((R) / 255.0f) green:((G) / 255.0f) blue:((B) / 255.0f) alpha:A]
#define RGBA_HexCOLOR(rgbValue, A) [UIColor colorWithRed:((float)((rgbValue & 0xFF0000) >> 16))/255.0 green:((float)((rgbValue & 0xFF00) >> 8))/255.0 blue:((float)(rgbValue & 0xFF))/255.0 alpha:A]
#define RandomColor RGBA_COLOR(arc4random_uniform(256),arc4random_uniform(256),arc4random_uniform(256),1)

@interface AQUpgradeView ()

/** 取消遮罩层 */
- (void)disMiss;

@property (nonatomic, strong) UIColor *coverColor; /**< 遮罩层颜色 */
@property (nonatomic, assign) BOOL touchDisMiss; /**< 触摸阴影层消失,默认=YES */
@property (nonatomic, copy) void (^touchDidDisMiss)(void); /**< touchDisMiss=YES 时有效 */

@property (nonatomic, weak) UIView *contentView;  // 背景View
@property (nonatomic, copy) NSString *upgradeUrl; // 升级链接

@end

@implementation AQUpgradeView

#pragma mark - LifeCycle

- (instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
        _touchDisMiss = YES;
        
        [self setupUI];
    }
    return self;
}

#pragma mark - setupUI

- (void)setupUI
{
    self.backgroundColor = UIColor.clearColor;
    
    UIView *contentView = [[UIView alloc] init];
    contentView.backgroundColor = [UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:0.5];
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction)];
    [contentView addGestureRecognizer:tap];
    [self addSubview:contentView];
    _contentView = contentView;
    [_contentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self);
    }];
}

#pragma mark - setupData

- (void)setCoverColor:(UIColor *)coverColor
{
    _coverColor = coverColor;
    self.contentView.backgroundColor = _coverColor;
}

- (void)tapAction
{
    if (self.touchDisMiss) {
        [self disMiss];
        if (self.touchDidDisMiss) {
            self.touchDidDisMiss();
        }
    }
}

- (void)disMiss
{
    if (self.superview) {
        [self removeFromSuperview];
    }
}

- (void)buttonAction:(UIButton *)btn
{
    if (btn.tag == 100) {
        // 暂不更新
        [UIView animateWithDuration:0.3 animations:^{
               self.alpha = 0;
           } completion:^(BOOL finished) {
               [self disMiss];
        }];
    } else {
        [AQUpgradeView openScheme:self.upgradeUrl handler:nil];
    }
}

#pragma mark - Class Method

+ (AQUpgradeView *)setupView:(NSString *)upgradeContent upgradeUrl:(NSString *)upgradeUrl version:(NSString *)version isForceUpgrade:(BOOL)isforceUpgrade
{
    AQUpgradeView *updateBgView = [[AQUpgradeView alloc] initWithFrame:CGRectZero];
    updateBgView.touchDisMiss = NO;
    updateBgView.upgradeUrl = upgradeUrl;
    [[AQUpgradeView appWindow] addSubview:updateBgView];
    [updateBgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo([AQUpgradeView appWindow]);
        make.size.equalTo([AQUpgradeView appWindow]);
    }];
    
    UIImage *imageName = [UIImage imageNamed:@"com_upgrade@3x"];
    UIImageView *ImgView = [[UIImageView alloc] initWithImage:imageName];
    ImgView.contentMode = UIViewContentModeScaleAspectFit;
    ImgView.backgroundColor = UIColor.clearColor;
    ImgView.layer.cornerRadius = 8.0f;
    ImgView.layer.masksToBounds = YES;
    ImgView.userInteractionEnabled = YES;
    [updateBgView addSubview:ImgView];
    [ImgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.equalTo(updateBgView);
        make.size.mas_equalTo(ImgView.image.size);
    }];
    
    NSString *verStr = [@"V" stringByAppendingString:version];
    UILabel *upGradeNotiLabel = [AQUpgradeView labelWithTitle:verStr font:[UIFont boldSystemFontOfSize:15.0f] titleColor:UIColor.whiteColor];
    [ImgView addSubview:upGradeNotiLabel];
    upGradeNotiLabel.textAlignment = NSTextAlignmentCenter;
    [upGradeNotiLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(ImgView.mas_top).offset(120.0f);
        make.left.right.mas_equalTo(ImgView);
    }];
    
    UITextView *contentTextView = [AQUpgradeView textViewWithText:nil font:[UIFont systemFontOfSize:14.0] textColor:RGBA_HexCOLOR(0x333333, 1) delegate:nil];
    contentTextView.editable = NO;
    contentTextView.textAlignment = NSTextAlignmentCenter;
    contentTextView.backgroundColor = [UIColor clearColor];
    [ImgView addSubview:contentTextView];
    [contentTextView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(upGradeNotiLabel.mas_bottom).with.offset(15.0f);
        make.left.mas_equalTo(ImgView).offset(50.0f);
        make.right.mas_equalTo(ImgView).offset(-50.0f);
        make.bottom.mas_equalTo(ImgView.mas_bottom).offset(-82.0f);
    }];
    NSMutableParagraphStyle *paragraphStyle = [NSMutableParagraphStyle new];
    paragraphStyle.lineSpacing = 5;
    NSDictionary *attributes = @{NSFontAttributeName:[UIFont systemFontOfSize:14.0],
                                 NSParagraphStyleAttributeName:paragraphStyle
                                 };
    contentTextView.typingAttributes = attributes;
    contentTextView.text = upgradeContent;

    if (!isforceUpgrade) {
        UIButton *notUpgradeBtn = [AQUpgradeView buttonWithTitle:@"暂不更新" titleColor:RGBA_HexCOLOR(0x333333, 1) font:[UIFont systemFontOfSize:16.0f] target:updateBgView selector:@selector(buttonAction:)];
        notUpgradeBtn.layer.cornerRadius = 7.0f;
        notUpgradeBtn.layer.borderWidth = 1.0f;
        notUpgradeBtn.layer.borderColor =  RGBA_HexCOLOR(0xDEDEDE, 1.0).CGColor;
        notUpgradeBtn.tag = 100;
        [ImgView addSubview:notUpgradeBtn];
        [notUpgradeBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.bottom.mas_equalTo(ImgView.mas_bottom).offset(-20.0f);
            make.left.equalTo(ImgView).offset(34.0f);
            make.size.mas_equalTo(CGSizeMake(108, 42.0f));
        }];
        
        UIButton *upGradeBtn = [AQUpgradeView buttonWithTitle:@"立即升级" titleColor:UIColor.whiteColor font:[UIFont boldSystemFontOfSize:16.0f] target:updateBgView selector:@selector(buttonAction:)];
        upGradeBtn.layer.cornerRadius = 7.0f;
        [upGradeBtn setTitleColor:UIColor.whiteColor forState:UIControlStateNormal];
        upGradeBtn.backgroundColor = RGBA_HexCOLOR(0x4949EF, 1);
        upGradeBtn.tag = 101;
        [ImgView addSubview:upGradeBtn];
        [upGradeBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.bottom.mas_equalTo(ImgView.mas_bottom).offset(-20.0f);
            make.right.equalTo(ImgView).offset(-34.0f);
            make.size.mas_equalTo(CGSizeMake(108, 42.0f));
        }];

        [@[notUpgradeBtn, upGradeBtn] mas_distributeViewsAlongAxis:MASAxisTypeHorizontal withFixedSpacing:22 leadSpacing:20 tailSpacing:20];
    } else {
        UIButton *upGradeBtn = [AQUpgradeView buttonWithTitle:@"立即升级" titleColor:UIColor.whiteColor font:[UIFont boldSystemFontOfSize:16.0f] target:updateBgView selector:@selector(buttonAction:)];
        upGradeBtn.layer.cornerRadius = 7.0f;
        [upGradeBtn setTitleColor:UIColor.whiteColor forState:UIControlStateNormal];
        upGradeBtn.backgroundColor = RGBA_HexCOLOR(0x4949EF, 1);
        upGradeBtn.tag = 101;
        [ImgView addSubview:upGradeBtn];
        [upGradeBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.bottom.mas_equalTo(ImgView.mas_bottom).offset(-20.0f);
            make.centerX.equalTo(ImgView);
            make.size.mas_equalTo(CGSizeMake(108, 42.0f));
        }];
    }
    
    return updateBgView;
}

+ (UIWindow *)appWindow {
    UIWindow *window = [[UIApplication sharedApplication] keyWindow];
    //app Window的windowLevel默认是UIWindowLevelNormal
    if (!window || window.windowLevel != UIWindowLevelNormal) {
        NSArray *windows = [[UIApplication sharedApplication] windows];
        for(UIWindow * tmpWin in windows) {
            if (tmpWin.windowLevel == UIWindowLevelNormal) {
                window = tmpWin;
                break;
            }
        }
    }
    return window;
}

+ (UILabel *)labelWithTitle:(NSString *)title font:(UIFont *)font titleColor:(UIColor *)titleColor {
    UILabel *label = [[UILabel alloc] init];
    label.textColor = titleColor;
    label.font = font;
    label.text = title;
    return label;
}

+ (UITextView *)textViewWithText:(NSString *)text font:(UIFont *)font textColor:(UIColor *)textColor delegate:(id<UITextViewDelegate>)delegate {
    UITextView *textView = [[UITextView alloc] init];
    textView.text = text;
    textView.textColor = textColor;
    textView.delegate = delegate;
    if (font != nil) {
        textView.font = font;
    }
    return textView;
}

+ (UIButton *)buttonWithTitle:(NSString *)title titleColor:(UIColor *)titleColor font:(UIFont *)font target:(id)target selector:(SEL)selector {
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    [btn addTarget:target action:selector forControlEvents:UIControlEventTouchUpInside];
    [btn setTitle:title forState:UIControlStateNormal];
    [btn setTitleColor:titleColor forState:UIControlStateNormal];
    if (font) {
        btn.titleLabel.font = font;
    }
    return btn;
}

/** 通过scheme调用相应功能
 
 @param scheme 协议
 @param handler 回调处理
 */
+ (void)openScheme:(NSString *)scheme handler:(nullable void (^)(BOOL success))handler {
    UIApplication *application = [UIApplication sharedApplication];
    NSString *str = [self hlf_stringAddingPercentEscapesChineseSpace:scheme];
    NSURL *url = [NSURL URLWithString:str];
    if (url && [application canOpenURL:url]) {
        if (@available(iOS 10.0, *)) {
            [application openURL:url options:@{} completionHandler:^(BOOL success) {
                if (handler) {
                    handler(success);
                }
            }];
        } else {
            BOOL flag = [[UIApplication sharedApplication] openURL:url];
            if (handler) {
                handler(flag);
            }
        }
    } else {
        if (handler) {
            handler(NO);
        }
    }
}

+ (NSString *)hlf_stringAddingPercentEscapesChineseSpace:(NSString *)url {
    if (!url.length) {
        return url;
    }
    
    NSString *regex = @".*[\u4e00-\u9fa5《》（）【】].*";
    NSPredicate *pre = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
    
    __block NSString *urlStr = [url copy];
    BOOL isIllegal = [pre evaluateWithObject:urlStr];
    if (isIllegal) {
        __block NSMutableDictionary *keyValueDict = [NSMutableDictionary dictionary];
        NSString *regex = @"[\u4e00-\u9fa5《》（）【】]";
        NSRegularExpression *regular = [NSRegularExpression regularExpressionWithPattern:regex options:NSRegularExpressionCaseInsensitive error:NULL];
        [regular enumerateMatchesInString:urlStr options:NSMatchingReportProgress range:NSMakeRange(0, urlStr.length) usingBlock:^(NSTextCheckingResult * _Nullable result, NSMatchingFlags flags, BOOL * _Nonnull stop) {
            if (result) {
                NSString *kv = [urlStr substringWithRange:result.range];
                
                keyValueDict[kv] = [kv stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
            }
        }];
        
        [keyValueDict enumerateKeysAndObjectsUsingBlock:^(id  _Nonnull key, id  _Nonnull obj, BOOL * _Nonnull stop) {
            urlStr = [urlStr stringByReplacingOccurrencesOfString:key withString:obj];
        }];
    }
    
    return [urlStr stringByReplacingOccurrencesOfString:@" " withString:@""];
}

@end

